import { DBNames } from '@/enum/dbName'
import { pageList, IPageListParams } from '@/api/commonInstance'

export interface ISelectParams {
  templateName: string
}

export default (params: ISelectParams) => {
  const { templateName } = params
  const mixin = {
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      idList: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        dataList: [],
        conditions: {},

        pagination: {
          pageNum: 1,
          pageSize: 10,
        },
        // isShowDialog: false,
        loading: false,
        total: 0,
      }
    },
    watch: {
      visible(val: boolean) {
        if (val) {
          // @ts-ignore
          this.fetchData()
        }
      },
    },
    mounted() {
      // @ts-ignore
      this.fetchData()
    },
    computed: {
      isShowDialog: {
        get(): boolean {
          // @ts-ignore
          return this.visible
        },
        set(val: boolean) {
          // @ts-ignore
          this.$emit('update:visible', val)
        },
      },
      localIds: {
        get(): string[] {
          // @ts-ignore
          return [...this.idList]
        },
        set(val: string[]) {
          console.log(val)
          // this.$emit('update:idList', val)
        },
      },
    },

    methods: {
      open() {
        this.fetchData()
        // @ts-ignore
        this.isShowDialog = true
      },

      async fetchData() {
        const {
          conditions,
          pagination: { pageNum, pageSize },
        } = this as any

        const params: IPageListParams = {
          conditions,
          pageInfo: { pageNum, pageSize },
          templateName: DBNames[templateName],
        }
        // @ts-ignore
        this.loading = true
        // @ts-ignore
        const { list, total } = await pageList(params)
        // @ts-ignore
        this.dataList = list
        // @ts-ignore
        this.total = total
        // @ts-ignore
        this.loading = false
      },

      handleChecked(checked: boolean, row: any) {
        const { id, _id } = row
        if (checked) {
          // @ts-ignore
          this.localIds.push(_id || id)
        } else {
          // @ts-ignore
          const index = this.localIds.findIndex((d) => d === _id || d === id)
          // @ts-ignore
          this.localIds.splice(index, 1)
        }
      },

      handleOk() {
        // @ts-ignore
        this.$emit('update:idList', [...this.localIds])
        // @ts-ignore
        this.isShowDialog = false
      },
    },
  }

  return mixin
}
